package com.esm.sm800.activity;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.esm.sm800.R;
import com.esm.sm800.database.dbmodel.Draw_report;
import com.esm.sm800.database.manager.DrawreportCenter;
import com.esm.sm800.sm800floating.FtpUploadUtil;
import com.esm.sm800.sm800floating.GlobalUtil;
import com.esm.sm800.util.Utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableImage;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
import zuo.biao.library.base.BaseActivity;
import zuo.biao.library.base.BaseAdapter;
import zuo.biao.library.base.BaseView;
import zuo.biao.library.model.Entry;

//借针报表
public class ReportjzActivity extends BaseActivity implements View.OnClickListener {

    private final String TAG = "ReportjzActivity";

    private ListView lv_hpcode;

    private TextView editText_startdate, editText_enddate, tv_gong;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.activity_reportjz);
        findViewById(R.id.tv_back).setOnClickListener(this);
        findViewById(R.id.tv_search).setOnClickListener(this);
        findViewById(R.id.ckbb_report_start_time).setOnClickListener(this);
        findViewById(R.id.ckbb_report_end_time).setOnClickListener(this);
        findViewById(R.id.tv_daochu).setOnClickListener(this);


        lv_hpcode = (ListView) findViewById(R.id.lv_hpcode);
        editText_startdate = findViewById(R.id.ckbb_report_start_time);
        editText_enddate = findViewById(R.id.ckbb_report_end_time);

        tv_gong = findViewById(R.id.tv_gong);

        onSearch();

        _adapter.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {
                onSelect(pos);
            }
        });
    }

    private void onSelect(int pos) {

    }

    void updateData() {
        setList(getList());

        tv_gong.setText(getString(R.string.ckbb_report_total_t) + _demodataList.size());
    }

    private ReportAdapter _adapter;

    private void setList(List<Entry<Integer, String>> list) {
        if (list == null) {
            return;
        }
        if (_adapter == null) {
            _adapter = new ReportAdapter(context);
            lv_hpcode.setAdapter(_adapter);
        }
        _adapter.refresh(list);
    }

    private List<Entry<Integer, String>> _demodataList;

    protected List<Entry<Integer, String>> getList() {
        _demodataList = new ArrayList<Entry<Integer, String>>();
        for (int i = 0; i < DrawreportCenter.getInstance().drlist.size(); i++) {
            _demodataList.add(new Entry<Integer, String>(i, ""));
        }
        return _demodataList;
    }

    public static final int FINISH_REPORT = 1101;
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == FINISH_REPORT) {
                dismissProgressDialog();
                showShortToast(getString(R.string.ydcbb));
            }
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.tv_back:
                finish();
                break;
            case R.id.tv_search:
                onSearch();
                break;
            case R.id.ckbb_report_start_time:
                showDatePickerDialog(1);
                break;
            case R.id.ckbb_report_end_time:
                showDatePickerDialog(2);
                break;
            case R.id.tv_daochu:
                onExport();
                break;
        }
    }

    private String _usbESMPath = "";     // U盘的ESM工作目录

    private boolean createESMDirectory() {
        //外接SD卡目录 /mnt/udisk
        File newDir = new File("/mnt/udisk");
        if (!newDir.exists()) {
            return false;
        }

        File newDir2 = new File("/mnt/udisk/esm");
        boolean isok = false;
        if (!newDir2.exists()) {
            isok = newDir2.mkdirs();
        } else {
            isok = true;
        }

        if (isok) {
            _usbESMPath = "/mnt/udisk/esm";
        }

        return true;

    }

    private void onExport() {
        if (Utils.isFastDoubleClick()) {
            return;
        }

        if (_usbESMPath.length() < 1) {
            if (!createESMDirectory()) {
                showShortToast(getString(R.string.ckbb_insert_U));
                return;
            }
        }

        //导出报表
        showProgressDialog(getString(R.string.zzdcbb));
        new Thread() {
            @Override
            public void run() {
                doExport();
                mHandler.sendEmptyMessage(FINISH_REPORT);
            }
        }.start();

    }

    private void doExport() {
        // 获取当前日期
        String filePathName = _usbESMPath + File.separatorChar + getString(R.string.ckbb_jz_title) + GlobalUtil.getCurrentDate() + ".xls";
        FileOutputStream output = null;
        try {
            output = new FileOutputStream(filePathName);
            WritableWorkbook wwb = jxl.Workbook.createWorkbook(output);
            WritableSheet sheet = wwb.createSheet("data", 0);

            // 格式
            WritableFont font = new WritableFont(WritableFont.createFont("宋体"),
                    8, WritableFont.NO_BOLD);// 字体样式
            WritableCellFormat wcf = new WritableCellFormat(font);
            wcf.setAlignment(jxl.format.Alignment.CENTRE);//平行居中
            wcf.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE); //垂直居中
            wcf.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN, jxl.format.Colour.BLACK); //BorderLineStyle边框

            // 第一行的行高
            sheet.setRowView(0, 500);
            // 序号
            sheet.addCell(new Label(0, 0, getString(R.string.ckbb_report_sheet_xh), wcf));
            sheet.setColumnView(0, 10);
            // 姓名
            sheet.addCell(new Label(1, 0, getString(R.string.ckbb_report_sheet_xm), wcf));
            sheet.setColumnView(1, 15);
            // 时间
            sheet.addCell(new Label(2, 0, getString(R.string.ckbb_report_sheet_sj), wcf));
            sheet.setColumnView(2, 30);
            // 借针时间
            sheet.addCell(new Label(3, 0, getString(R.string.ckbb_report_sheet_jzsj), wcf));
            sheet.setColumnView(3, 30);
            // 组号
            sheet.addCell(new Label(4, 0, getString(R.string.ckbb_report_sheet_zh), wcf));
            sheet.setColumnView(4, 15);
            // 款号
            sheet.addCell(new Label(5, 0, getString(R.string.ckbb_report_sheet_kh), wcf));
            sheet.setColumnView(5, 15);
            // 工序
            sheet.addCell(new Label(6, 0, getString(R.string.ckbb_report_sheet_gx), wcf));
            sheet.setColumnView(6, 15);
            // 颜色
            sheet.addCell(new Label(7, 0, getString(R.string.ckbb_report_sheet_ys), wcf));
            sheet.setColumnView(7, 15);
            // 尺码
            sheet.addCell(new Label(8, 0, getString(R.string.ckbb_report_sheet_cm), wcf));
            sheet.setColumnView(8, 15);
            // 批号
            sheet.addCell(new Label(9, 0, getString(R.string.ckbb_report_sheet_ph), wcf));
            sheet.setColumnView(9, 15);
            // 机针型号
            sheet.addCell(new Label(10, 0, getString(R.string.ckbb_report_sheet_jzxh), wcf));
            sheet.setColumnView(10, 15);
            // 状态
            sheet.addCell(new Label(11, 0, getString(R.string.ckbb_report_sheet_zt), wcf));
            sheet.setColumnView(11, 15);
            // 通过人
            sheet.addCell(new Label(12, 0, getString(R.string.ckbb_report_sheet_tgr), wcf));
            sheet.setColumnView(12, 15);
            // 机台编号
            sheet.addCell(new Label(13, 0, getString(R.string.ckbb_report_sheet_jtbh), wcf));
            sheet.setColumnView(13, 15);
            // 机针状态
            sheet.addCell(new Label(14, 0, getString(R.string.ckbb_report_sheet_jzzt), wcf));
            sheet.setColumnView(14, 30);
            // 还针照片
//            sheet.addCell(new Label(15, 0, getString(R.string.hzpic), wcf));
//            sheet.setColumnView(15, 30);

            int i = 1;
            for (Draw_report dr : DrawreportCenter.getInstance().drlist) {
                sheet.setRowView(i, 500);
                // 序号
                sheet.addCell(new Label(0, i, i + "", wcf));
                sheet.setColumnView(0, 10);
                // 姓名
                sheet.addCell(new Label(1, i, dr.getMember(), wcf));
                sheet.setColumnView(1, 15);
                // 时间
                sheet.addCell(new Label(2, i, dr.getReturn_time(), wcf));
                sheet.setColumnView(2, 30);
                // 借针时间
                sheet.addCell(new Label(3, i, dr.getCreat_time(), wcf));
                sheet.setColumnView(3, 30);
                // 组号
                sheet.addCell(new Label(4, i, dr.getMemberremark(), wcf));
                sheet.setColumnView(4, 15);
                // 款号
                sheet.addCell(new Label(5, i, dr.getXstyle(), wcf));
                sheet.setColumnView(5, 15);
                // 工序
                sheet.addCell(new Label(6, i, dr.getXgongxu(), wcf));
                sheet.setColumnView(6, 15);
                // 颜色
                sheet.addCell(new Label(7, i, dr.getXcolor(), wcf));
                sheet.setColumnView(7, 15);
                // 尺码
                sheet.addCell(new Label(8, i, dr.getXsize(), wcf));
                sheet.setColumnView(8, 15);
                // 批号
                sheet.addCell(new Label(9, i, dr.getXpihao(), wcf));
                sheet.setColumnView(9, 15);
                // 机针型号
                sheet.addCell(new Label(10, i, dr.getNeedle_name(), wcf));
                sheet.setColumnView(10, 15);
                // 状态
                sheet.addCell(new Label(11, i, "已还针", wcf));
                sheet.setColumnView(11, 15);
                // 通过人
                sheet.addCell(new Label(12, i, dr.getTgr(), wcf));
                sheet.setColumnView(12, 15);
                // 机台编号
                sheet.addCell(new Label(13, i, dr.getJtname(), wcf));
                sheet.setColumnView(13, 15);
                // 机针状态
                sheet.addCell(new Label(14, i, dr.getNeedle_status(), wcf));
                sheet.setColumnView(14, 30);
                // 还针照片
//                try {
//                    Bitmap bitmap = BitmapFactory.decodeFile(dr.getImg());
//                    if (bitmap != null) {
//                        byte[] imageData = bitmapToByteArray(bitmap);
//                        WritableImage image = new WritableImage(15, i, 1, 1, imageData);
//                        sheet.addImage(image);
//                        bitmap.recycle();
//                    }
//                } catch (OutOfMemoryError e) {
//                    // 处理内存不足的情况，例如通过释放一些资源或降低图片质量
//                    e.printStackTrace();
//                }

                i++;
            }

            output.flush();
            wwb.write(); //写入数据
            wwb.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (RowsExceededException e) {
            throw new RuntimeException(e);
        } catch (WriteException e) {
            throw new RuntimeException(e);
        }

        if (output != null) {
            try {
                output.close();
                uploadFTP();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static byte[] bitmapToByteArray(Bitmap bitmap) {
        if (bitmap != null) {
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
            return stream.toByteArray();
        }
        return null;
    }

    // 上传到FTP服务器
    private void uploadFTP() {
        String SourcefileFullPathName = _usbESMPath + File.separatorChar + getString(R.string.ckbb_jz_title) + GlobalUtil.getCurrentDate() + ".xls";
        File file = new File(SourcefileFullPathName);
        if (!file.exists()) {
            return;
        }

        String DestFTPfileName =  "Borrow_" + GlobalUtil.getCurrentDate() + ".xls";//不能用中文

        if (GlobalUtil.ishasdataupload_swtich)
            startFtpUpload(SourcefileFullPathName, DestFTPfileName);
    }

    private void startFtpUpload(String SourcefileFullPathName, String DestFTPfileName) {
        new Thread(() -> {
            GlobalUtil.getFTPLogin(getApplicationContext());
            if (GlobalUtil.Key_ftpserverip_value.isEmpty() ||
                    GlobalUtil.Key_ftpserveruser_value.isEmpty() ||
                    GlobalUtil.Key_ftpserverpass_value.isEmpty()) {
                return;
            }
            // 在这里执行FTP上传操作
            new FtpUploadUtil(GlobalUtil.Key_ftpserverip_value, GlobalUtil.Key_ftpserveruser_value, GlobalUtil.Key_ftpserverpass_value, SourcefileFullPathName, DestFTPfileName, false).execute();
        }).start();
    }

    private void showDatePickerDialog(int k) {
        DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                // 在这里处理日期选择结果，例如更新EditText的文本
                String selectedDate = String.format("%04d-%02d-%02d", year, month + 1, dayOfMonth);
                if (k == 1)
                    editText_startdate.setText(selectedDate);
                else
                    editText_enddate.setText(selectedDate);
            }
        }, Calendar.getInstance().get(Calendar.YEAR), Calendar.getInstance().get(Calendar.MONTH), Calendar.getInstance().get(Calendar.DAY_OF_MONTH));

        datePickerDialog.show();
    }

    private void onSearch() {
        String startdate = editText_startdate.getText().toString();
        String enddate = editText_enddate.getText().toString();

        ArrayList<Draw_report> list = DrawreportCenter.getInstance().getDraw_reportlist(startdate, enddate, 0);
        DrawreportCenter.getInstance().drlist = list;
        updateData();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }

        if (requestCode == 200) {
            setResult(RESULT_OK);
            finish();
        }

    }


    @Override
    public void initView() {

    }

    @Override
    public void initData() {

    }

    @Override
    public void initEvent() {

    }

    public class ReportAdapter extends BaseAdapter<Entry<Integer, String>, ReportView> {

        public ReportAdapter(Activity context) {
            super(context);
        }

        @Override
        public ReportView createView(int position, ViewGroup parent) {
            return new ReportView(context, parent);
        }

        @Override
        public long getItemId(int position) {
            return getItem(position).getId();
        }

//    @Override
//    public boolean isEnabled(int position) {
//        //设置不可点击，否则enter按键无法响应
//        return false;
//    }

    }

    public class ReportView extends BaseView<Entry<Integer, String>> {
        private static final String TAG = "ReportView";

        public ReportView(Activity context, ViewGroup parent) {
            super(context, R.layout.reportjz_view, parent);
        }

        public TextView tv_id;
        public TextView tv_date;
        public TextView tv_needlename;
        public TextView tv_remark;
        public TextView tv_position;
        public TextView tv_member;

        @Override
        public View createView() {
            tv_id = findView(R.id.tv_id);
            tv_member = findView(R.id.tv_member);
            tv_date = findView(R.id.tv_date);
            tv_remark = findView(R.id.tv_remark);
            tv_needlename = findView(R.id.tv_needlename);

            return super.createView();
        }

        @Override
        public void bindView(Entry<Integer, String> data_) {
            super.bindView(data_ != null ? data_ : new Entry<Integer, String>());
//        itemView.setBackgroundResource(selected ? R.drawable.alpha3 : R.drawable.white_to_alpha);
            int index = data.getKey();
            if (index < DrawreportCenter.getInstance().drlist.size()) {
                Draw_report dr = DrawreportCenter.getInstance().drlist.get(index);
                tv_id.setText("" + (index + 1));
                tv_member.setText(dr.getMember());
                tv_date.setText(dr.getCreat_time());
                tv_remark.setText(dr.getMemberremark());
                tv_needlename.setText(dr.getNeedle_name());

            }
        }

    }
}

